package com.sgb.kjwl.view.ui.activity.lease;

import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.KeyListener;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ViewLeaseGaodeSearchBinding;
import com.sgb.kjwl.model.LocationAddressInfo;
import com.sgb.kjwl.utils.KeyboardUtils;
import com.sgb.kjwl.view.ui.adapter.lease.GaodeSearchAdapter;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.List;

/**
 * 租赁首页高德地图搜索
 */
public class LeaseGaodeSearchView extends LinearLayout implements PoiSearch.OnPoiSearchListener
//        ,AMapLocationListener
{

    private List<LocationAddressInfo> historys = new ArrayList<>();
    private ArrayList<LocationAddressInfo> list = new ArrayList<>();

    private ViewLeaseGaodeSearchBinding binding;
    private GaodeSearchAdapter adapter;

    private String keyWord = "";// 要输入的poi搜索关键字
    private PoiResult poiResult; // poi返回的结果
    private int currentPage = 0;// 当前页面，从0开始计数
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;// POI搜索
    private String searchCity = "陕西省";//要搜索的城市

    //定位需要的声明
    private AMapLocationClient mLocationClient = null;//定位发起端
    private AMapLocationClientOption mLocationOption = null;//定位参数
    private boolean flag = false;
    private Context mContext;
    private EditText editText;
    private View delView;

    private KeyListener mKeyListener;

    private OnKeyListener onKeyListener = new OnKeyListener() {
        @Override
        public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
            if (keyCode == KeyEvent.KEYCODE_SEARCH || keyCode == KeyEvent.KEYCODE_ENTER) {
                keyWord = editText.getText().toString();
                if (TextUtils.isEmpty(keyWord)) {
                    MToast.showToast(mContext, "请输入关键字");
                } else {
                    // doSearchQuery(keyWord);
                    KeyboardUtils.hideSoftInput(editText);
                }
                return true;
            }
            return false;
        }
    };

    public LeaseGaodeSearchView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        initView();
    }

    private void initView() {
        binding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.view_lease_gaode_search, this, true);
//        model = new AskLeaseLayoutModel(mContext, this);
//        initListener();
        init();
//        initLoc();
    }


    public void setEditText(EditText editText,View view) {
        this.editText = editText;
        this.delView = view;
        initEdit();
    }
    public void setSearchCity(String searchCity) {
        this.searchCity = searchCity;
    }

    protected void init() {

        adapter = new GaodeSearchAdapter(mContext, list);
        binding.rv.setAdapter(adapter);
        adapter.setCallback(bean -> {
            binding.rv.setVisibility(GONE);
            KeyboardUtils.hideSoftInput((Activity) mContext);
//            if (bean.getTip() != 2) {
//                bean.setTip(1);
//                if (!historys.contains(bean)) {
//                    historys.add(bean);
//                    if (historys.size() > 10) {//最多保存10条历史记录,超过10条,删除最早的记录
//                        historys.remove(0);
//                    }
//                    String json = new Gson().toJson(historys);
//                    SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.ZULIN_MAP_ADDR_SEARCH_HISTORY, json);
//                }
//            }
//            if("图选".equals(bean.getTitle())){
//                //跳转到地图选点确认界面
//                Bundle bundle = new Bundle();
//                bundle.putString("title", bean.getTitle());
//                bundle.putString("text", bean.getText());
//                bundle.putDouble("lat", bean.getLat());
//                bundle.putDouble("lon", bean.getLon());
//                LeaseUseMapActivity.start(getActivity(), bundle);
//                finish();
//            }else{
//            Bundle bundle = new Bundle();
//            bundle.putString("title", bean.getTitle());
//            bundle.putString("text", bean.getText());
//            bundle.putDouble("lat", bean.getLat());
//            bundle.putDouble("lon", bean.getLon());
                if(listener!=null){
                    listener.onCall(bean.getTitle(),bean.getLat(),bean.getLon());
                }
//            if (flag) {
//                LeaseHallMapActivity.startForBundle(getActivity(), bundle);
//                finish();
//            } else {
//                Intent intent = new Intent();
//                intent.putExtras(bundle);
//                setResult(RESULT_OK, intent);
//                finish();
//            }

//            }

        });

//        initEdit();
//        getHistoryList();
    }

    private void initEdit() {
        mKeyListener = editText.getKeyListener();
        editText.setKeyListener(null);
        editText.setOnKeyListener(onKeyListener);
        editText.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus){
                    editText.setKeyListener(mKeyListener);
                    String s = editText.getText().toString();
                    editText.setText(s);
                } else {
                    editText.setKeyListener(null);
                    editText.requestLayout();
                    editText.postInvalidate();
                }
            }
        });
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(!KeyboardUtils.isSoftInputVisible((Activity) mContext)){
                    return;
                }
                keyWord = editText.getText().toString();
                if (!TextUtils.isEmpty(keyWord)) {
                    doSearchQuery(keyWord);
                    delView.setVisibility(VISIBLE);
                } else {
                    binding.rv.setVisibility(View.GONE);
                    delView.setVisibility(GONE);
//                    getHistoryList();
                }
            }
        });
    }


//    private void getHistoryList() {
//        //取出本地存的搜索记录
//        String historyWords = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.ZULIN_MAP_ADDR_SEARCH_HISTORY, "");
//        Gson gson = new Gson();
//        Type type = new TypeToken<List<LocationAddressInfo>>() {
//        }.getType();
//        list.clear();
//        List<LocationAddressInfo> hs = gson.fromJson(historyWords, type);
////        list.add(new LocationAddressInfo("图选", "可以在地图上选择使用地点哦！", 0.0, 0.0, "", 2));
//        if (hs != null) {
//            Collections.reverse(hs);
//            historys.addAll(hs);
//            list.addAll(hs);
//        }
//        adapter.notifyDataSetChanged();
//        binding.rv.setVisibility(View.VISIBLE);
////        binding.itmeEmpty.setVisibility(View.GONE);
//    }


//    //定位
//    private void initLoc() {
//        //初始化定位
//        mLocationClient = new AMapLocationClient(mContext.getApplicationContext());
//        //设置定位回调监听
//        mLocationClient.setLocationListener(this);
//        //初始化定位参数
//        mLocationOption = new AMapLocationClientOption();
//        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
//        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//        //设置是否返回地址信息（默认返回地址信息）
//        mLocationOption.setNeedAddress(true);
//        //设置是否只定位一次,默认为false
//        mLocationOption.setOnceLocation(false);
//        //设置是否强制刷新WIFI，默认为强制刷新
//        mLocationOption.setWifiActiveScan(true);
//        //设置是否允许模拟位置,默认为false，不允许模拟位置
//        mLocationOption.setMockEnable(false);
//        //设置定位间隔,单位毫秒,默认为2000ms
//        mLocationOption.setInterval(2000);
//        //给定位客户端对象设置定位参数
//        mLocationClient.setLocationOption(mLocationOption);
//        //启动定位
//        mLocationClient.startLocation();
//    }


    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery(String key) {
        currentPage = 0;
        query = new PoiSearch.Query(key, "", searchCity);
        query.setPageSize(10);
        query.setPageNum(currentPage);
        poiSearch = new PoiSearch(mContext, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();//发起检索请求
    }


    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        //rCode 为1000 时成功,其他为失败
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            // 解析result   获取搜索poi的结果
            if (result != null && result.getQuery() != null) {
                if (result.getQuery().equals(query)) {  // 是否是同一条
                    poiResult = result;
                    ArrayList<LocationAddressInfo> data = new ArrayList<LocationAddressInfo>();//自己创建的数据集合
                    // 取得第一页的poiitem数据，页数从数字0开始
                    //poiResult.getPois()可以获取到PoiItem列表
                    List<PoiItem> poiItems = poiResult.getPois();


                    //解析获取到的PoiItem列表
                    for (PoiItem item : poiItems) {
                        //获取经纬度对象
                        LatLonPoint llp = item.getLatLonPoint();
                        double lon = llp.getLongitude();
                        double lat = llp.getLatitude();
                        //返回POI的名称
                        String title = item.getTitle();
                        //返回POI的地址
                        String text = item.getSnippet();
                        data.add(new LocationAddressInfo(title, text, lon, lat, keyWord, 0));
                    }
                    list.clear();
                    list.addAll(data);
//                    list.add(new LocationAddressInfo("图选", "没有找到合适使用地点，可以在地图上选择哦！", 0, 0, "", 2));
                    adapter.notifyDataSetChanged();
                    if (list.size() > 1 && !TextUtils.isEmpty(keyWord) && keyWord.length() > 0) {
                        binding.rv.setVisibility(View.VISIBLE);
//                        binding.itmeEmpty.setVisibility(View.GONE);
                    } else {
                        binding.rv.setVisibility(View.GONE);
//                        binding.itmeEmpty.setVisibility(View.VISIBLE);
                    }

                }
            } else {
//                MToast.showToast(mContext, "无搜索结果");
                binding.rv.setVisibility(View.GONE);
//                binding.itmeEmpty.setVisibility(View.VISIBLE);
            }
        } else {
//            MToast.showToast(mContext, "暂无搜索结果");
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }


//    @Override
//    public void onLocationChanged(AMapLocation amapLocation) {
//        if (amapLocation != null) {
//            if (amapLocation.getErrorCode() == 0) {
//                searchCity = amapLocation.getProvince();//省信息
//                // amapLocation.getCity();//城市信息
//            }
//        }
//    }

    public void setOnClallListener(CallListener listener) {
        this.listener = listener;
    }

    public CallListener listener;

    public interface CallListener {
        void onCall(String address,double lat,double lon);
    }
}
